package com.xzl.serviceribbon.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xzl.serviceribbon.HelloService;
import com.xzl.serviceribbon.HiDTO;
import com.xzl.serviceribbon.MyHealthChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HelloContronller {
    @Autowired
    private LoadBalancerClient loadBalancer;
    @Autowired
    HelloService helloService;
    @Autowired
    MyHealthChecker myHealthChecker;
    @Autowired
    RestTemplate restTemplate;

    @Value("${server.port}")
    String port;

    @RequestMapping("/bCallA")
    public String hi(@RequestParam String name) throws JsonProcessingException, InterruptedException {
//        String token = SecurityContextHolder.getContext().getAuthentication().getCredentials().toString();
//        ResultResponse resultResponse = helloService.hiService(name, token);
        return "1";
    }

    @RequestMapping("/test")
    public String hiF(@RequestParam String name) throws JsonProcessingException, InterruptedException {
        loadBalancer.choose("service-hi").getUri().toString();
//        restTemplate.getForObject("http://172.18.20.202:8783/hiya",String.class);
        HiDTO hiDTO = new HiDTO();
        hiDTO.setName("jay");
        hiDTO.setPwd("123456");
        hib("jay");
        return restTemplate.getForObject("http://SERVICE-HI:8783/hiya",String.class);
    }

    @RequestMapping("/bCallAu")
    public String hiAu()  {
        restTemplate.exchange("https://AUTH-SERVER/auth", HttpMethod.GET, null, new ParameterizedTypeReference<String>() {});
        return restTemplate.getForObject("https://AUTH-SERVER/auth",String.class);
    }

    @RequestMapping("/hib")
    public String hib(@RequestParam String name) throws InterruptedException {
//        Thread.sleep(4000);
        return "2";
    }

    @RequestMapping("/up")
    public String up(@RequestParam("up") Boolean up) {
        myHealthChecker.setUp(up);
        return up.toString();
    }

    @GetMapping("/deregist")
    public String deregist(@RequestParam("id")String id) {
        return helloService.deregist(id);
    }

    @GetMapping("/regist")
    public String regist(@RequestParam("id")String id) {
        return helloService.regist(id);
    }
}
